<html>
<script type="text/javascript">
var storage = {
    get:function(key){
        try{
          return JSON.parse(localStorage[key]); 
        }
        catch(e){return ''}
    },
    //synced : server to client
    set:function(key, value, synced){
        try{
            localStorage[key] = JSON.stringify(value);
            !synced && (needSyncStorage = true);
            return true;
        }
        catch(e){return false;}
    }
};
var getNextPageTabId = null, masterTabId = null, needSyncStorage = false, _m = chrome.i18n.getMessage;
var baseUrl = 'http://os.heimali.com/HappyReader/',
    listUrl = baseUrl + 'list.php',
    intfUrl = baseUrl + 'index.php';

chrome.browserAction.onClicked.addListener(function(tab){
    chrome.tabs.sendRequest(tab.id, {'callExtMode':'browseAction'}, function(response) {});
});

chrome.extension.onRequestExternal.addListener(function(request, sender, sendResponse){
    if (sender.id == 'kfbkjmofblefhdbabmjfecidcglggoaa' && request.cmd == 'openWebElement'){
        chrome.tabs.getSelected(undefined, function(tab){
            chrome.tabs.sendRequest(tab.id, {'callExtMode':'mouseGesture'}, function(response) {});
        })
        sendResponse({});
    }
});

chrome.extension.onRequest.addListener(
    function(request, sender, sendResponse) {
        if (request.action == "sendTextToCloud") {
            sendTextToCloud(request, function(res){
                sendResponse(res);
            });
        }
});

chrome.extension.onConnectExternal.addListener(connectionHandler);
chrome.self.onConnect.addListener(connectionHandler);
function connectionHandler(port){
    port.onMessage.addListener(function(msg,conn){
        switch(msg.action){
            case 'getOptions':
                port.postMessage(getOptions());
                break;
            case 'getOptionsHotKey':
                port.postMessage({
                    options_hotkey: storage.get('options_hotkey')
                });
                break;
            case 'getOptionsEnableAnalysisHelper':
                port.postMessage({
                    options_enableAnalysisHelper: storage.get('options_enableAnalysisHelper')
                });
                break;
            case 'setOptionsEnableAnalysisHelper':
                storage.set('options_enableAnalysisHelper', parseInt(msg.value));
                break;
            case 'getOptionsEnableSuperAutoNextPage':
                port.postMessage({
                    options_enableSuperAutoNextPage: storage.get('options_enableSuperAutoNextPage')
                });
                break;
            case 'setOptionsEnableSuperAutoNextPage':
                storage.set('options_enableSuperAutoNextPage', parseInt(msg.value));
                break;
            case 'isTabForNextPage':
                port.postMessage({
                   isTabForNextPage: conn.tab.id == getNextPageTabId
                });
                break;
            case 'getNextPageContent':
                if (getNextPageTabId === null){
                    chrome.tabs.create({url:msg.url, selected:false},function(tab){getNextPageTabId=tab.id});
                    masterTabId = conn.tab.id;
                }
                break;
            case 'setNextPageContent':
                chrome.tabs.connect(masterTabId).postMessage({action:"setNextPageContent" , content: msg.content});
                break;
            case 'noNextPageContent':
                chrome.tabs.remove(getNextPageTabId, function(tab){getNextPageTabId=null});
                chrome.tabs.connect(masterTabId).postMessage({action:"noNextPageContent"});
                break;
            case 'setTextSkin':
                storage.set('setting_textSkin', msg.textSkin);
                var selfTabID = conn.tab.id;
                chrome.tabs.getAllInWindow(null, function(tabs){
                    tabs.forEach(function(tab, idx){
                        if (tab.id != selfTabID) {
                            chrome.tabs.connect(tab.id).postMessage({action: "updateTextSkin",textSkin: msg.textSkin});
                        }
                    })
                })
                break;
            case 'getTextSkin':
                port.postMessage({'textSkin': storage.get('setting_textSkin')});
                break;
			case 'getUserInfo':
			    port.postMessage({'userInfo': storage.get('user_info')});
				break;
        }
    });
};

function getOptions(){
    return {
        setting_textSkin: storage.get('setting_textSkin') || {bg:'#fff', fontSize:'16px', pageWidth:'800'},
        options_hotkey: storage.get('options_hotkey'),
        options_enableAnalysisHelper: storage.get('options_enableAnalysisHelper'),
        options_enableSuperAutoNextPage: storage.get('options_enableSuperAutoNextPage')
    };
}
/* string url, string data, string type, function callback */
function ajax(url, data, type, callback){
    var type = (type.toLowerCase()=='get') ? 'GET' : 'POST',
        data = data.replace(/\+/g, '*add*'),
        request = new XMLHttpRequest();
    
    request.open(type, url);
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
    request.onreadystatechange = function() {
        try {
            if (this.readyState == XMLHttpRequest.DONE) {
                callback(JSON.parse(this.responseText));
            }
        }catch(e){
            callback({suc:'-2', errmsg:'Cloud service is busy !<br/>Please try again later.'})
        }
    };
    request.send(data||null);
}

function syncStorage(){
    var userInfo = storage.get('user_info');
    if (userInfo.uid) {
        var url = intfUrl+"?type=setConf&uid="+userInfo.uid+"&token="+userInfo.token,
            data = 'conf='+JSON.stringify(getOptions());
        ajax(url, data, 'post',  function(res){needSyncStorage = false});
    }
}
function sendTextToCloud(msg, callback){
    var userInfo = storage.get('user_info');
    if (userInfo.uid) {
        var url = intfUrl + "?type=setArticle&uid=" + userInfo.uid + "&token=" + userInfo.token, 
        data = "surl=" + msg.url + "&mytitle=" + msg.title + "&intro="+ msg.intro +"&content=" + encodeURIComponent(msg.content);
        ajax(url, data, 'POST', callback);
    }else{
        callback({suc:0, msg:'<a href="'+chrome.extension.getURL('options.html')+'" style="color:yellow" target="_blank">'+_m('login')+'</a>'});
    }
}

(function(){
    var userInfo = storage.get('user_info');
    if (!userInfo.uid || !userInfo.token)return;
    
    var url = intfUrl+"?type=getConf&uid="+userInfo.uid+"&token="+userInfo.token+"&r="+Math.random(1,100000);
    ajax(url, '', 'get', function(res){
        try {
            if(res.suc == '1' && res.data){
                var data = JSON.parse(res.data);
                for (var key in data) {
                    storage.set(key, data[key], true);
                }
            }
        }catch(e){}
    });
})();

setInterval(function(){
    needSyncStorage && syncStorage();
}, 1000*60);
</script>
</html>
